<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <!-- <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
      </image> -->
      <text class="title">新用户注册</text>
    </view>

    <uni-section title="">
      <view class="example">
        <!-- 基础表单校验 -->
        <uni-forms ref="valiForm" :rules="rules" :modelValue="registerForm" label-position="top">
          <uni-forms-item label="用户类型" required name="userType">
            <uni-data-select v-model="registerForm.userType" :localdata="range" label="请选择用户类型"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="用户名" required name="nickName">
            <uni-easyinput v-model="registerForm.nickName" placeholder="请输入用户名" />
          </uni-forms-item>
          <uni-forms-item label="密码" required name="password">
            <uni-easyinput v-model="registerForm.password" placeholder="请输入密码" />
          </uni-forms-item>
          <uni-forms-item label="确认密码" required name="confirmPassword">
            <uni-easyinput v-model="registerForm.confirmPassword" placeholder="请再次输入密码" />
          </uni-forms-item>
          <uni-forms-item label="邮箱" required name="email">
            <uni-easyinput v-model="registerForm.email" placeholder="请输入邮箱" />
          </uni-forms-item>
          <uni-forms-item label="姓名" required name="userName">
            <uni-easyinput v-model="registerForm.userName" placeholder="请输入姓名" />
          </uni-forms-item>
          <uni-forms-item label="手机号" name="phoneNumber">
            <uni-easyinput v-model="registerForm.phoneNumber" placeholder="请输入手机号" />
          </uni-forms-item>
            <uni-forms-item label="性别">
                <uni-data-checkbox v-model="registerForm.sex" :localdata="sexs"/>
            </uni-forms-item>
            <uni-forms-item label="出生日期">
                <uni-datetime-picker type="date" :clear-icon="false" v-model="registerForm.birthday"/>
            </uni-forms-item>
			<uni-forms-item label="公司名称/学校名称" required name="company">
			  <view class="custom-select">
			    <input 
			      v-model="searchKeyword" 
			      type="text" 
			      placeholder="请输入公司学校名称" 
			      @input="handleCompanyInput"
				  @focus="showDropdown = true"
			    />
				<view>
					<view class="search-icon" v-if="!searchKeyword">
						<u-icon name="arrow-down" size="14" color="#c0c4cc"></u-icon>
					</view>
					<view class="search-icon" v-if="searchKeyword" @click="delKeyWord">
						<u-icon name="close-circle-fill" size="20" color="#c0c4cc"></u-icon>
					</view>
				</view>
			    <view v-show="showDropdown" class="dropdown">
			      <view v-if="filteredCompanyList.length > 0">
					  <view
						class="dropdown-view"
					    v-for="(item, index) in filteredCompanyList" 
					    :key="index" 
					    @click="selectCompany(item)"
					  >
					   {{ item.text }}
					  </view>
				  </view>
				  <view class="dropdown-view" v-if="filteredCompanyList.length == 0">无匹配数据</view>
			    </view>
			  </view>
			</uni-forms-item>
            <!-- <uni-forms-item label="公司名称/学校名称" required name="company">
                <uni-data-select v-model="registerForm.company" :localdata="filteredCompanyList"
                                 label="请选择公司学校名称"></uni-data-select>
            </uni-forms-item> -->
            <uni-forms-item name="companyName" v-if="registerForm.company == 44 || registerForm.company == otherId">
                <uni-easyinput v-model="registerForm.companyName" placeholder="请输入公司学校名称"/>
            </uni-forms-item>
            <uni-forms-item label="专业" required name="profession">
                <uni-data-select v-model="registerForm.profession" :localdata="majorList"
                                 label="请选择专业"></uni-data-select>
            </uni-forms-item>
        </uni-forms>
        <button type="primary" @click="submit('valiForm')">提交</button>
      </view>
    </uni-section>

    <view class="xieyi text-center">
      <text @click="handleUserLogin" class="text-blue">使用已有账号登录</text>
    </view>
  </view>
</template>

<script>
import { getCodeImg, register } from "@/api/login";

export default {
  data() {
    return {
      codeUrl: "",
      captchaEnabled: true,
      globalConfig: getApp().globalData.config,
      range: [
        {
          value: 1,
          text: "所外学生用户",
        },
        {
          value: 2,
          text: "所外企业用户",
        },
      ],
      sexs: [
        {
          value: 1,
          text: "男",
        },
        {
          value: 2,
          text: "女",
        },
      ],
      registerForm: {
          userName: '',
          password: '',
          type: 1,
          sex: 1
      },
      majorList: [],
	  companyList:[],
	  filteredCompanyList: [], // 用于存储过滤后的公司列表
	  otherId: '',
	  searchKeyword: '',
	  showDropdown: false,
      // 校验规则
      rules: {
        userType: {
          rules: [
            {
              required: true,
              errorMessage: "用户类型不能为空",
            },
          ],
        },
        nickName: {
          rules: [
            {
              required: true,
              errorMessage: "用户名不能为空",
            },
            {
              minLength: 2,
              maxLength: 20,
              errorMessage: "用户名长度再 2-20 之间",
            },
          ],
        },
        userName:{
          rules: [
            {
              required: true,
              errorMessage: "姓名不能为空",
            },
            {
              minLength: 2,
              maxLength: 10,
              errorMessage: "姓名长度再 2-10之间",
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: "密码不能为空",
            },
            {
              minLength: 8,
              maxLength: 20,
              errorMessage: "密码长度应在 8-20 之间",
            },
          ],
        },
        confirmPassword: {
          rules: [
            {
              required: true,
              errorMessage: "确认密码不能为空",
            },
            {
              validateFunction: (rule, value, data, callback) => {
                if (value !== data.password) {
                  callback("两次输入的密码不一致");
                } else {
                  callback();
                }
              },
            },
          ],
        },
        email: {
          rules: [
            {
              required: true,
              errorMessage: "邮箱不能为空",
            },
            {
              format: "email",
              errorMessage: "邮箱格式不正确",
            },
          ],
        },
        phoneNumber: {
          rules: [
            {
              pattern: /^1[0-9][0-9]\d{8}$/,
              errorMessage: "请输入正确的手机号码",
            },
          ],
        },
          company: {
              rules: [
                  {
                      required: true,
                      errorMessage: '公司/学校名称不能为空'
                  }
              ]
          },
          companyName: {
              rules: [
                  {
                      required: true,
                      errorMessage: '请输入公司/学校名称'
                  }
              ]
          },
          profession: {
              rules: [
                  {
                      required: true,
                      errorMessage: '专业不能为空'
                  }
              ]
          }
      },
    };
  },
  created() {
    this.majorType();
	this.companyFn();
  },
  methods: {
    // 用户登录
    handleUserLogin() {
      this.$tab.navigateTo(`/pages/login`);
    },
    // 专业类型
    majorType() {
		this.majorTypeList = [];
      this.$request({
        url: "/dict/register/major",
        method: "get",
      }).then(({ data }) => {
        console.log("查看专业类型", data);
        // this.majorList = data;
        data.map((item) => {
          this.majorList.push({
            value: item.id,
            text: item.name,
          });
        });
      });
    },
	// 公司信息列表
	companyFn(){
		this.companyList = [];
      this.$request({
        url: "/dict/register/company",
        method: "get",
      }).then(({ data }) => {
        console.log("查看专业类型", data);
        data.map((item) => {
          this.companyList.push({
            value: item.id,
            text: item.name,
          });
        });
		this.filteredCompanyList = this.companyList
		const otherItem = data.find(item => item.dictCode == 'other');
		if (otherItem) {
		  this.otherId = otherItem.id;
		} else {
		  console.warn('未找到 name 为 "其他" 的项');
		}
		console.log(this.companyList)
      });
	},
	// 处理公司名称输入事件
	handleCompanyInput(value) {
		console.log(value.detail.value, 'value')
	  if (value.detail.value) {
		this.showDropdown = true;
	    this.filteredCompanyList = this.companyList.filter(item => 
	      item.text.includes(value.detail.value)
	    );
	  } else {
		// this.showDropdown = false;
	    this.filteredCompanyList = this.companyList; // 如果没有输入，显示全部
	  }
	  console.log(this.filteredCompanyList)
	},
	// 选择公司
	selectCompany(item) {
		console.log(item)
	  this.registerForm.company = item.value;
	  this.searchKeyword = item.text;
	  this.showDropdown = false;
	},
	delKeyWord() {
		this.registerForm.company = '';
		this.searchKeyword = '';
		this.showDropdown = false;
		this.filteredCompanyList = this.companyList;
	},
	handleChangeCompany(value) {
		console.log(value)
	},
    // 注册方法
    submit(ref) {
		console.log(this.registerForm)
        if (this.registerForm.company != 44 && this.registerForm.company != this.otherId) {
            this.registerForm.companyName = ''
        }
        this.$refs[ref]
                .validate()
                .then((res) => {
                    console.log('注册信息', this.registerForm)
                
                    this.$request({
                        url: '/user/register',
                        method: 'post',
                        data: this.registerForm
                    }).then(({data}) => {
            console.log("success", data);
            uni.$toast("注册成功");
            setTimeout(() => {
              uni.redirectTo({
                url: `/pages/login`,
              });
            }, 1000);
          });
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .no-label {
    height: 0;
}

.uni-stat__select {
    background: white !important;
}

::v-deep .uni-forms-item__label {
  width: 300rpx !important;
}

.normal-login-container {
  width: 100%;
  height: 100%;
  // position: absolute;
  background-image: url("../static/images/login_bg.svg");
  background-size: 100%;
  background-repeat: no-repeat;
  // background-color: #e5eff7;
  padding: 29rpx;

  .uni-section {
    background: none !important;
  }

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 15%;

    image {
      border-radius: 4px;
    }

    .title {
      margin-left: 10px;
    }
  }

  .login-form-content {
    text-align: center;
    margin: 20px auto;
    width: 80%;

    .input-item {
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 10px;

      .icon {
        font-size: 38rpx;
        margin-left: 10px;
        color: #999;
      }

      .input {
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        padding-left: 15px;
      }
    }

    .register-btn {
      margin-top: 40px;
      height: 45px;
    }

    .xieyi {
      color: #333;
      margin-top: 20px;
    }

    .login-code {
      height: 38px;
      float: right;

      .login-code-img {
        height: 38px;
        position: absolute;
        margin-left: 10px;
        width: 200rpx;
      }
    }
  }

  .text-center {
    margin-top: 22rpx;
  }
  .custom-select {
    position: relative;
	::v-deep .input-placeholder {
		font-size: 24rpx;
		color: #6a6a6a;
	}
    ::v-deep input {
      width: 100%;
      height: 70rpx;
      padding: 0 20rpx;
      box-sizing: border-box;
      border: 2rpx solid #e5e5e5;
	  background: #fff;
      border-radius: 8rpx;
	  font-size: 28rpx;
	  color: #333;
    }
	.search-icon {
		position: absolute;
		right: 12rpx;
		top: 22rpx;
	}
    .dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      border-top: none;
      max-height: 200px;
      overflow-y: auto;
      z-index: 10;
      box-sizing: border-box;
      background-color: #FFFFFF;
      border: 1px solid #EBEEF5;
      border-radius: 6px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      z-index: 3;
      padding: 4px 0;
      .dropdown-view {
        padding: 10px;
        cursor: pointer;
        &:hover {
          background: #f0f0f0;
        }
      }
    }
  }
}
</style>
